/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package library;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 *
 * @author ryan
 */
public class User {
    private static int nextId = 0;
    private final int id;
    private final String name;
    private final Set<Item> checkedOutItems;
    private final Type t;
    private final List<InventoryChangeListener> listeners;
    
    public enum Type{
        ADULT,
        CHILD
    }
    
    public User(String name, Type t)
    {
        this(nextId++, name, t);
    }
    
    public User(int id, String name, Type t)
    {
        this.id = id;
        nextId = nextId > id ? nextId : id + 1;
        this.name=name;
        checkedOutItems= new HashSet<Item>();
        listeners = new ArrayList<InventoryChangeListener>();
        this.t=t;        
    }
    
    
    public void fireUpdateListeners(){
        for(InventoryChangeListener l:listeners){
            l.onChange();
        }       
    }
    
    /**
     * 
     * @return ID of user
     */
    public int getId(){
        return id;        
    }
    
    /**
     * 
     * @return Name of user
     */
    public String getName(){
        return name;        
    }
    
    /**
     * Add an item to the user
     * @param item 
     */
    public void addItem(Item item){
        this.checkedOutItems.add(item);
        for(InventoryChangeListener l:listeners){
           l.onChange();
        }
    }
    
    
    /**
    * Add an item to the user
    * @param item 
    */
    public void removeItem(Item item){
        this.checkedOutItems.remove(item);
        for(Item i:checkedOutItems){
            System.out.println("ITEM " +i);
        }
        for(InventoryChangeListener l:listeners){
           l.onChange();
        }
    }
    

    
    public InventoryChangeListener addInventoryChangeListener(InventoryChangeListener l){
        this.listeners.add(l);
        return l;
    }
    
    public void removeInventoryChangeListener(InventoryChangeListener l){
        this.listeners.remove(l);
    }
    
    /**
     * Returnsa list of all the users overdue items given the date
     * @param d
     * @return 
     */
    public Set<Item> getOverdueItems(Date d){
        Set<Item> overdue = new HashSet<Item>();
        for(Item i:checkedOutItems){
            if(i.getDueDate().after(d)){
                overdue.add(i);
            }
        }
        return overdue;
    }
    
    /**
     * Returns the user type (Adult, Child)
     * @return 
     */
    public Type getType(){
        return t;
    }
    
    /**
     * Returns all the items the user has checked out
     * @return 
     */
    public Set<Item> getItems(){
        return new HashSet<Item>(checkedOutItems);
    }    
    
    @Override
    public String toString(){
        return name+ " "+t.toString();
    }
}